package cn.lblbc.appassit.utils

import android.content.Context
import android.os.Environment
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

object FileUtils {
    
    @Deprecated("Use getExportDirectory(context: Context) instead")
    fun getDefaultExportDirectory(): String {
        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath
    }

    fun getExportDirectory(context: Context): String {
        val sharedPreferencesHelper = SharedPreferencesHelper(context)
        return sharedPreferencesHelper.getExportDirectory()
    }
    
    fun isDirectoryWritable(directoryPath: String): Boolean {
        return try {
            val directory = File(directoryPath)
            directory.exists() && directory.isDirectory && directory.canWrite()
        } catch (e: Exception) {
            false
        }
    }
    
    fun getPathFromUri(context: Context, uri: android.net.Uri): String? {
        return try {
            // 简单实现：对于文档树URI，尝试获取路径
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                val documentId = android.provider.DocumentsContract.getTreeDocumentId(uri)
                if (documentId.startsWith("primary:")) {
                    val path = documentId.substringAfter("primary:")
                    return Environment.getExternalStorageDirectory().absolutePath + "/" + path
                }
            }
            null
        } catch (e: Exception) {
            null
        }
    }
    

    fun formatFileSize(size: Long): String {
        if (size <= 0) return "0 B"
        val units = arrayOf("B", "KB", "MB", "GB", "TB")
        val digitGroups = (Math.log10(size.toDouble()) / Math.log10(1024.0)).toInt()
        return String.format("%.1f %s", size / Math.pow(1024.0, digitGroups.toDouble()), units[digitGroups])
    }
    
    fun formatDate(timestamp: Long, pattern: String = "yyyy-MM-dd HH:mm:ss"): String {
        return SimpleDateFormat(pattern, Locale.getDefault()).format(Date(timestamp))
    }
    
    fun sanitizeFileName(fileName: String): String {
        return fileName.replace(Regex("[\\\\/:*?\"<>|]"), "_")
    }
    
    fun getAvailableStorageSpace(): Long {
        return try {
            val externalDir = Environment.getExternalStorageDirectory()
            externalDir.freeSpace
        } catch (e: Exception) {
            0L
        }
    }
    
    fun isExternalStorageWritable(): Boolean {
        return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
    }
}